<!-- 编辑弹窗 -->
<template>
  <div class="ele-body">
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      :title="isUpdate ? '修改模板' : '添加模板'"
      :visible="visible"
      custom-class="ele-dialog-form"
      width="740px"
      @open="opened"
      @close="closed"
      @update:visible="updateVisible"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="82px">
        <el-form-item label="模板名称:" prop="name">
          <el-input
            v-model="form.name"
            :maxlength="20"
            clearable
            placeholder="请输入模板名称"
          />
        </el-form-item>

        <el-form-item label="效果图:" prop="image">
          <el-upload
            list-type="picture-card"
            :limit="5"
            :on-exceed="imgexceed"
            :headers="headersUpload"
            :file-list="imgFileList"
            :on-success="imgsuccess"
            :on-error="imgerrorUpload"
            :action="imgbaseURLUpload()"
            :before-upload="imgbeforeUpload"
            :on-preview="imghandlePictureCardPreview"
            :on-remove="imghandleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="模板源码:" prop="source">
          <el-input
            v-model="form.source"
            clearable
            placeholder="请上传模板源码"
            style="width: 534px"
          />
          <el-upload
            :action="zipbaseURLUpload()"
            :headers="headersUpload"
            :before-upload="zipbeforeUpload"
            :disabled="zipuploadLoading"
            :on-error="ziperrorUpload"
            :on-progress="zipprogressUpload"
            :on-success="zipsuccessUpload"
            :show-file-list="false"
            style="position: relative; display: inline-block; margin-left: 10px"
          >
            <el-button
              :disabled="zipuploadLoading"
              :loading="zipuploadLoading"
              icon="el-icon-upload"
              size="small"
              style="width: 74px; height: 34px"
              type="primary"
              >{{ zipuploadText }}
            </el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="模板备注:">
          <el-input
            v-model="form.remark"
            :maxlength="200"
            :rows="3"
            clearable
            placeholder="请输入模板备注"
            type="textarea"
          />
        </el-form-item>

        <el-form-item label="排序:">
          <el-input-number
            v-model="form.sort"
            :max="9999"
            :min="1"
            class="ele-fluid ele-text-left"
            controls-position="right"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="状态:">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="updateVisible(false)">取消 </el-button>
        <el-button :loading="loading" type="primary" @click="save"
          >确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看效果图" :visible.sync="imgdialogVisible">
      <img width="600px" height="560px" :src="imgdialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import setting from "@/config/setting";
export default {
  name: "TemplatesEdit",
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
  },
  data() {
    return {
      // 表单数据
      form: Object.assign(
        {
          name: "",
          image: "",
          source: "",
          remark: "",
          sort: 0,
          status: 1,
        },
        this.data
      ),
      // 表单验证规则
      rules: {
        name: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
        image: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.imgFileList.length === 0) {
                return callback(new Error("请上传模板封面图"));
              }
              callback();
            },
          },
        ],
        source: [
          { required: true, message: "请上传模板源码", trigger: "blur" },
        ],
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      // 封面图上传
      imgFileList: [],
      imgdisabled: false,
      imgdialogImageUrl: "",
      imgdialogVisible: false,
      headersUpload: {
        Authorization: setting.takeToken(),
      },
      // 上传标题
      zipuploadText: "上传",
      // 上传状态
      zipuploadLoading: false,
    };
  },
  watch: {
    data() {
      if (Object.keys(this.data).length > 0) {
        this.form = Object.assign(
          {},
          {
            name: "",
            image: "",
            source: "",
            remark: "",
            sort: 0,
            status: 1,
          },
          this.data
        );
        this.isUpdate = true;
      } else {
        for (let i in this.form) {
          this.form[i] = null;
        }
        this.sort = 0;
        this.image = "";
        this.form.status = 1;
        this.isUpdate = false;
        this.imgFileList = [];
      }
    },
  },
  methods: {
    opened() {
      this.imgFileList = [];
      if (this.form.image) {
        if (this.form.image.length > 0) {
          for (let i = 0; i < this.form.image.length; i++) {
            this.imgFileList.push(this.form.image[i]);
          }
        }
      }
    },
    closed() {
      this.imgFileList = [];
    },

    imgbaseURLUpload() {
      return process.env.VUE_APP_API_BASE_URL + "/templates/imageUpload";
    },

    imghandleRemove(file, fileList) {
      this.imgFileList = fileList;
    },

    imgerrorUpload() {
      this.$message.error("上传失败!");
    },

    imghandlePictureCardPreview(file) {
      this.imgdialogImageUrl = file.url;
      this.imgdialogVisible = true;
    },

    imgexceed() {
      this.$message.error("你最多只能上传5张图片!");
    },

    imgsuccess(response, file, fileList) {
      this.imgFileList = fileList;
      if (response.code != 0) {
        this.$message.error("上传失败!");
        if (this.imgFileList.length > 0) {
          this.imgFileList.pop();
        }
      }
    },

    imgbeforeUpload(file) {
      const fileType = file.type.toLowerCase();
      if (
        [
          "image/jpeg",
          "image/bmp",
          "image/gif",
          "image/png",
          "image/webp",
          "image/tiff",
        ].indexOf(fileType) === -1
      ) {
        this.$message.error("上传文件只能是图片格式!");
        return false;
      }
      if (!(file.size / 1024 / 1024 < 2)) {
        this.$message.error("上传文件大小不能超过2MB!");
        return false;
      }
      return true;
    },

    zipbaseURLUpload() {
      return process.env.VUE_APP_API_BASE_URL + "/templates/zipUpload";
    },

    zipbeforeUpload(file) {
      const isZip = file.type === "application/x-zip-compressed";
      if (!isZip) {
        this.$message.error("上传文件只能是 Zip 格式!");
        return false;
      }
      const isLt15M = file.size / 1024 / 1024 < 15;
      if (!isLt15M) {
        this.$message.error("上传文件大小不能超过 15MB!");
        return false;
      }
      const valid = isZip && isLt15M;
      if (valid) {
        this.zipuploadLoading = true;
      }
      return valid;
    },
    ziperrorUpload() {
      this.zipuploadText = "上传";
      this.zipuploadLoading = false;
      this.$message.error("上传失败!");
    },
    zipsuccessUpload(obj) {
      this.zipuploadText = "上传";
      this.zipuploadLoading = false;
      if (obj.code === 0) {
        this.form.source = obj.url;
        this.$message({
          message: "上传成功!",
          type: "success",
        });
      } else {
        this.$message.error(obj.msg);
      }
    },
    zipprogressUpload(event) {
      if (event.isTrusted) {
        this.zipuploadText = parseInt(event.percent) + "%";
      }
    },

    save() {
      let imageArray = [];
      for (let i = 0; i < this.imgFileList.length; i++) {
        imageArray.push({
          name: this.imgFileList[i].name,
          url: this.imgFileList[i].response
            ? this.imgFileList[i].response.url
            : this.imgFileList[i].url,
        });
      }
      this.form.image = JSON.stringify(imageArray);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$http
            .post(
              "/templates/" + [this.isUpdate ? "edit" : "create"],
              this.form
            )
            .then((res) => {
              this.loading = false;
              if (res.data.code === 0) {
                this.$message({ type: "success", message: res.data.msg });
                if (!this.isUpdate) {
                  for (let i in this.form) {
                    this.form[i] = null;
                  }
                  this.form.status = 1;
                }
                this.updateVisible(false);
                this.$emit("done", this.isUpdate);
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit("update:visible", value);
    },
  },
};
</script>
<style scoped>
.ele-body /deep/ .el-upload--picture-card {
  width: 96px;
  height: 96px;
  line-height: 96px;
}

.ele-body /deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 96px;
  height: 96px;
}
</style>
